import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { map, Observable } from 'rxjs';

@Injectable()
export class SerializeInterceptor implements NestInterceptor {
  private defaultExclude = true; // 私有属性
  private options = {};
  constructor(
    private dto: any,
    defaultExclude: boolean,
    options: any,
  ) {
    this.defaultExclude = defaultExclude;
    this.options = options;
  }
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map((data) => {
        return plainToInstance(this.dto, data, {
          // 自定义参数
          ...this.options,

          // 设置为true，表示经过该拦截器的接口，只返回dto中有设置@Expose的属性，没有的属性不返回
          // @Expose 设置那些需要响应，@Exclude 设置那些不需要响应,优先级高
          excludeExtraneousValues: this.defaultExclude,
        });
      }),
    );
  }
}
